﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Project.BIZ;
using Project.IBIZ;
using Project.DTO;

namespace Project.UI
{
    public partial class ProductList : System.Web.UI.Page
    {
        #region "Global variables"

        /// <summary>
        /// Global instance from ProductList Business layer
        /// </summary>
        IProductListBIZ ProductListBiz = new ProductListBIZ();

        /// <summary>
        /// Indentify current page index
        /// </summary>
        public int CurrentPage
        {
            get
            {
                object page = this.ViewState[Constants.CurrentPageViewState];
                // Show the first page by default
                if (page == null || (int)page < 0)
                {
                    return 0;
                }
                else
                {
                    return (int)page;
                }
            }
            set
            {
                // Set current page to the one that is being referred
                this.ViewState[Constants.CurrentPageViewState] = value;
            }
        }

        #endregion

        #region "Event methods"

        /// <summary>
        /// Display product list of a specific category as first time loading page
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            LoadData();
        }

        /// <summary>
        /// Handle event when changing page index
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvProduct_PageIndexChanging
                (object sender, GridViewPageEventArgs e)
        {
            gvProduct.PageIndex = e.NewPageIndex;
            LoadData();
        }

        #endregion 

        #region "Support methods"

        /// <summary>
        /// Load data of a list of products from database
        /// </summary>
        private void LoadData()
        {
            // Take category ID from address bar
            int categoryId = 0;
            int.TryParse(Request.QueryString[Constants.CatIdFromAddressBar], out categoryId);

            try
            {
                clPager.PageSize = 4;
                clPager.DataSource = ProductListBiz.LoadProductList(categoryId);
                clPager.BindToControl = dlProduct;
                dlProduct.DataSource = clPager.DataSourcePaged;
                dlProduct.DataBind();
            }
            catch (Exception) { }
        }

        #endregion
    }
}